<?php
namespace IKPHP\Common\Models;

use IKPHP\Common\Models\BaseModel;
use IKPHP\Common\Models\User;
use IKPHP\Common\Models\VirtualModel;

class Comment extends BaseModel
{
	public $cid;
	public $referid;
	public $typeid;
	public $type;
	public $userid;
	
    public function getSource()
    {
        return IK."comment";
    }
	//Refer二级循环，三级循环暂时免谈 获取评论
	public static function recomment($referid){
		
		$strComment = self::FindFirst("cid= '$referid'");
		$strcmt = array();
		if($strComment){
			$strcmt = $strComment->toArray(); 
			$strcmt['user'] = User::getOneUser($strcmt['userid']); 
			$strcmt['content'] = nl2br($strcmt['content']);
		}
		return $strcmt;
	} 
	//删除的单个或多个评论$commentid='1,2,3' 以逗号分隔
	public static function delComment($commentid){
		$arr_id = explode(',', $commentid);
		if(is_array($arr_id)){
			foreach ($arr_id as $val){
				$strChild = self::findFirst("referid = '$val'"); 
				if($strChild){
					self::findFirst("cid = '$val'")->save(array('isdelete'=>1));
				}else{
					self::findFirst("cid = '$val'")->delete();
				}
			}
		}
		return true;
	}
	//删除后跟新其他表
    public function afterDelete()
    {
        //更新模型记录集
        $vimodel = new VirtualModel(); 
		$vimodel->setviSource($this->type); 
		$pkey = $vimodel->getPk(); 
		$strMod = $vimodel->findFirst("$pkey = $this->typeid"); 
		if($strMod){ 
			if($strMod->count_comment>0){
				$strMod->count_comment --;
				$strMod->save();
			}
		}
    }
    //更新后重新计算评论
    public function afterSave(){
    	//计算评论数
    	$count = self::count("typeid='$this->typeid' AND isdelete=0");
        //更新模型记录集
        $vimodel = new VirtualModel();
		$vimodel->setviSource($this->type);
		$pkey = $vimodel->getPk();
		$strMod = $vimodel->findFirst("$pkey = $this->typeid"); 
		$strMod->count_comment = $count;
		$strMod->uptime = time();
		$strMod->save();  	
    }
	//获取最新回应type typeid 要知道有哪些typeid type
	public static function getNewComment($where,$limit = 10){
		$res = self::find(array('conditions'=>$where, 'order'=>'addtime desc', 'limit'=>$limit));
		$result  = array();
		foreach ($res->toArray() as $key=>$item){
			$result[] = $item;
			$result[$key]['user'] = User::getOneUser($item['userid']);
		}
		return $result;
	}    	   
}
